<?php

namespace Backend\Controllers;

use Models\User;


class SignController extends BaseController
{

    public function loginAction()
    {
        if ($this->request->isPost() == true) {
            if ($this->security->checkToken()) {
                $username = $this->request->getPost("username");
                $password = $this->request->getPost("password");
                if (!$username || !$password) return $this->flashSession->warning("您必须输入用户名和密码以登录");
                $user = User::findFirstByUsername($username);
                if ($user) {
                    if($user->status==0)return $this->flashSession->warning("用户禁用请联系管理员");
                    if($user->role_id!=3)return $this->flashSession->warning("此页面为普通用户登陆界面");
                    if ($this->security->checkHash($password, $user->password)) {
                        $user->lastip = $this->request->getClientAddress();
                        $user->lastlogin = time();
                        $user->save();
                        $this->session->start();

                        $this->session->set('user', $user->toArray());
                        return $this->response->redirect("admin/index");
                    } else {
                        return   $this->flashSession->warning("帐号密码不正确");
                    }
                } else {
                    return $this->flashSession->warning("用户不存在");
                }
            } else {
                return $this->flashSession->warning("Access Denied!");
            }
        }
    }

    public function logoutAction()
    {
//        $this->session->destroy();
        $this->flashSession->success("您已经成功退出");
        $this->cookies->set('auth', '');
        return $this->response->redirect("admin/sign/login");
    }


}